package logic

import (
	"fmt"
	"iot-base/auth/common/socket"
	"iot-base/auth/config"
	"iot-base/auth/db"
	"iot-base/auth/logger"
	"iot-base/auth/model/iot"
	"iot-base/auth/svc"
	types2 "iot-base/auth/types"
	"iot-base/auth/utils"
	"strconv"
)

type AlarmLogic struct {
}

func NewAlarmLogic() *AlarmLogic {
	return &AlarmLogic{}
}

// SendGroupAlarm 更具用户组来推送告警.
func (l *AlarmLogic) SendGroupAlarm(param types2.RespAlarm) {
	// 查询设备所在的组
	list, err := NewStationLogic().FindGroupStationsByStationId(param.StationId)
	if err != nil {
		fmt.Println("err", err)
		logger.Log.Errorf("SendGroupAlarm  err:%v req:%v", err, list)
		return
	}
	// 查询设备类型
	redis := db.NewRedis()
	key := "alarm:msgId:%v"
	// 广播消息.
	for _, value := range list {
		pushData := param
		pushData.GroupId = value.GroupId
		messageId, _ := redis.IncrBy(fmt.Sprintf(key, value.GroupId), 1)
		pushData.MessageId = messageId
		fmt.Println("pushData\n", pushData)
		utils.AntsPool.Submit(func() {
			socket.IoRoom.PushAlarmMsg(strconv.FormatInt(value.GroupId, 10), config.EventAlarm, pushData)
		})
	}
	// 管理员的消息.
	msgData := param
	messageId, _ := redis.IncrBy(fmt.Sprintf(key, config.SystemAdmin), 1)
	msgData.MessageId = messageId
	utils.AntsPool.Submit(func() {
		socket.IoRoom.PushAlarmMsg(strconv.FormatInt(config.SystemAdmin, 10), config.EventAlarm, msgData)
	})
}

func (l *AlarmLogic) SendEventMsg(param types2.RespEvent) {
	list, err := NewStationLogic().FindGroupStationsByStationId(param.StationID)
	if err != nil {
		fmt.Println("err", err)
		logger.Log.Errorf("SendGroupAlarm  err:%v req:%v", err, list)
		return
	}
	// 广播消息.
	for _, value := range list {
		utils.AntsPool.Submit(func() {
			socket.IoRoom.PushMsg(strconv.FormatInt(value.GroupId, 10), config.EventNotice, param)
		})
	}
	utils.AntsPool.Submit(func() {
		socket.IoRoom.PushMsg(strconv.FormatInt(config.SystemAdmin, 10), config.EventNotice, param)
	})
}

// ActiveAlarm 活动告警.
func (l *AlarmLogic) ActiveAlarm(userId int64, stationId string, page, size int, startTime string, endTime string) (map[string]interface{}, error) {
	resp := map[string]interface{}{
		"total": 0,
		"list":  []interface{}{},
	}
	isSysAdmin, err := NewUserLogic().IsSysAdmin(userId)
	if err != nil {
		return nil, err
	}
	var total int64
	var list []iot.AlarmState
	if isSysAdmin {
		total, err = svc.Dao.TAlarm.FindListCount(stationId, startTime, endTime)
		if err != nil {
			return resp, err
		}
		list, err = svc.Dao.TAlarm.FindList(stationId, page, size, startTime, endTime)
		if err != nil {
			return resp, err
		}
	} else {
		stationIds, err := NewStationLogic().GetStationIds(userId)
		if err != nil {
			return resp, nil
		}
		if stationId != "" {
			if in(stationId, stationIds) {
				stationIds = []string{stationId}
			} else {
				return resp, nil
			}
		}
		total, err = svc.Dao.TAlarm.FindByStationByIdsCount(stationIds, startTime, endTime)
		if err != nil {
			return resp, err
		}
		list, err = svc.Dao.TAlarm.FindByStationByIdsList(stationIds, page, size, startTime, endTime)
		if err != nil {
			return resp, err
		}
	}
	key := fmt.Sprintf("%s#%v", db.KeyAlarmTotal, userId)
	db.NewRedis().Set(key, total, 0)
	resp["total"] = total
	resp["list"] = list
	return resp, nil
}

func in(target string, strArray []string) bool {
	for _, element := range strArray {
		if target == element {
			return true
		}
	}
	return false
}
func (l *AlarmLogic) ActiveAlarmNum(userId int64) (int64, error) {
	var total int64
	isSysAdmin, err := NewUserLogic().IsSysAdmin(userId)
	if err != nil {
		return total, err
	}
	if isSysAdmin {
		total, err = svc.Dao.TAlarm.FindListCount("", "", "")
		if err != nil {
			return total, err
		}
	} else {
		stationIds, err := NewStationLogic().GetStationIds(userId)
		if err != nil {
			return total, nil
		}
		total, err = svc.Dao.TAlarm.FindByStationByIdsCount(stationIds, "", "")
		if err != nil {
			return total, err
		}
	}
	key := fmt.Sprintf("%s#%v", db.KeyAlarmTotal, userId)
	db.NewRedis().Set(key, total, 0)
	return total, nil
}

// HistoryAlarm 历史告警.
func (l *AlarmLogic) HistoryAlarm(userId int64, stationId string, page, size int, startTime string, endTime string) (map[string]interface{}, error) {
	resp := map[string]interface{}{
		"total": 0,
		"list":  []interface{}{},
	}
	isSysAdmin, err := NewUserLogic().IsSysAdmin(userId)
	if err != nil {
		return nil, err
	}
	if isSysAdmin {
		total, err := svc.Dao.TAlarmHistory.FindAllCount(stationId, startTime, endTime)
		if err != nil {
			return resp, err
		}
		list, err := svc.Dao.TAlarmHistory.FindAll(stationId, page, size, startTime, endTime)
		if err != nil {
			return resp, err
		}
		resp["total"] = total
		resp["list"] = list

	} else {
		stationIds, err := NewStationLogic().GetStationIds(userId)
		if err != nil {
			return resp, nil
		}
		// 单个条件查询
		if stationId != "" {
			if in(stationId, stationIds) {
				stationIds = []string{stationId}
			} else {
				return resp, nil
			}
		}

		total, err := svc.Dao.TAlarmHistory.FindByStationByIdsCount(stationIds, startTime, endTime)
		if err != nil {
			return resp, err
		}
		list, err := svc.Dao.TAlarmHistory.FindByStationByIdsList(stationIds, page, size, startTime, endTime)
		if err != nil {
			return resp, err
		}
		resp["total"] = total
		resp["list"] = list

	}
	return resp, nil
}

// GetStationAlarm 获取站点告警.
func (l *AlarmLogic) GetStationAlarm(stationId string) (map[string]interface{}, error) {
	resp := make(map[string]interface{})
	list, err := svc.Dao.TAlarm.FindByStationIdList(stationId)
	if err != nil {
		return resp, err
	}
	for _, v := range list {
		if _, ok := resp[v.CatalogID]; !ok {
			resp[v.CatalogID] = int(0)
		}
		resp[v.CatalogID] = resp[v.CatalogID].(int) + 1
	}
	key := fmt.Sprintf("%s#%v", db.KeySubStationAlarm, stationId)
	db.NewRedis().Del(key)
	db.NewRedis().HMSet(key, resp)
	return resp, nil
}
